package com.dartfar.base.action;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.dartfar.base.model.Function;
import com.dartfar.base.model.Person;
import com.dartfar.base.model.Role;
import com.dartfar.base.model.T_User;
import com.dartfar.base.service.FunctionService;
import com.dartfar.base.service.PersonService;
import com.dartfar.base.service.RoleService;
import com.dartfar.base.service.UserService;
import com.dartfar.base.vo.DataGridVo;
import com.dartfar.base.vo.FunctionVo;
import com.dartfar.base.vo.UserVo;
import com.dartfar.menu.model.Menu;
import com.dartfar.menu.service.MenuService;
import com.dartfar.organize.model.Department;
import com.dartfar.organize.service.DepartmentService;
import com.dartfar.permission.model.Permission;
import com.dartfar.permission.service.PermissionService;
import com.dartfar.util.ListUtil;
import com.dartfar.util.StringUtils;
import com.dartfar.util.SystemUtil;
import com.dartfar.util.W7;

/**
 * 用户Action对象
 * @author 刘毅
 */

@Component("userAction")
@Scope("prototype")
public class UserAction extends BaseAction{
	
	private static final long serialVersionUID = 1L;
	
	private static Logger logger = Logger.getLogger(UserAction.class);
	
	/**
	 * Service对象
	 */
	@Resource
	private UserService userService;
	@Resource
	private PersonService personService;
	@Resource
	private DepartmentService departService;
	@Resource
	private RoleService roleService;
	@Resource
	private MenuService menuService;
	@Resource
	private FunctionService functionService;
	@Resource
	private PermissionService permissionService;

	/**
	 * 页面传参
	 */
	private int id;
	private T_User user;
	private String result;
	private String loginName;
	private int departId;
	private int curDepartId;
	private String roles ;
	private String name;
	private String password;
	private String sex;
	private String sn;
	private String jobDate;
	private String birthday;
	private String status;
	private String locked;
	private String phone;
	private int pageNo;
	private int pageSize;
	private long totalCount;
	
	private List<FunctionVo> functions;
	
	


	/**
	 * 用户登录
	 */
	@SuppressWarnings("unchecked")
	public String login(){
		
		logger.info("用户登录开始=============================================================================================");
	
		try{
			//取得用户实体
			T_User loginUser = userService.getByName(name);
			if(loginUser == null){
				logger.info("用户不存在.");
				result = "userNull";
			}else if(!(loginUser.getPassword().equals(W7.encode(password)))){
				logger.info("登录密码错误.");
				result = "passwordError";
			}else if(loginUser.getStatus().equalsIgnoreCase("离职")){
				logger.info("用户已经离职.");
				result = "statusError";
			}else if(loginUser.getLocked().equalsIgnoreCase("是")){
				logger.info("用户被锁定.");
				result = "lockedError";
			}else if(loginUser.getPerson().getRoles().size() == 0){
				logger.info("用户角色异常.");
				result = "rolesError";
			}else{
				//判断登录用户是否为超级管理员
				if(loginUser.getId() == 1){
					//如果是超级管理员则判断登陆地址是否正确
					if(!SystemUtil.getIpAddress().equalsIgnoreCase("192.168.1.100")){
						logger.info("用户登录失败.");
						result = "error";
						return SUCCESS;
					}
				}
				
				logger.info("用户登录成功.");
				//人员
				Person person = loginUser.getPerson();
				//部门
				Department depart = person.getDepart();
	
				List<Menu> menus = new ArrayList<Menu>();
				List<Menu> subMenu = new ArrayList<Menu>();
				//List<Permission> permFunction = new ArrayList<Permission>();
				Map functionMap = new HashMap();
				
				String roleIds = "";
	
				//遍历登录用户的所有角色
				for(Iterator<Role> roles = person.getRoles().iterator();roles.hasNext();){
					Role role = roles.next();
					if (roleIds != "") roleIds += "','";
					roleIds += role.getRoleId();
				}
				//根据用户拥有的角色获取全部权限
				//List<Authority> authoritys = authorityService.getListByRoleMenuId(roleIds, 0, 0);
					
				logger.info("ROLES: " + roleIds);
				//roleIds = roleIds.replaceAll(",", "','");
				List<Permission> permissions = permissionService.getListByRoleIdOrMenuId(roleIds, null);
				logger.info("PERMISSIONS: " + permissions.size());
					
				//定义子菜单ID变量
				String menuIds = "";
				String funcIds = "";
				//遍历用户拥有的权限列表
				for(Iterator<Permission> perms = permissions.iterator(); perms.hasNext();){
					Permission perm = perms.next();
					//生成子菜单ID字符串
					if(menuIds != "") menuIds += ",";
					//菜单ID
					menuIds += perm.getMenuId();
					//功能ID
					funcIds = perm.getFunIds();
					//logger.info("menuId: " + perm.getMenuId() + "funcIds: " + funcIds);
					//如果集合中出现重复菜单
					if(functionMap.containsKey("menu" + perm.getMenuId())){
						//取出已经存在的功能
						funcIds = (String) functionMap.get("menu" + perm.getMenuId()) + ",";
						//追加新功能
						funcIds += perm.getFunIds();
						logger.info("add funcIds: " + funcIds);
						//删除重复功能
						funcIds = StringUtils.removeRepeat(funcIds);
						//logger.info("menuId: " + perm.getMenuId() + "    remove funcIds：" + funcIds);
						//再写入集合
						functionMap.put("menu" + perm.getMenuId(), funcIds);
					}else{
						//写入集合
						functionMap.put("menu" + perm.getMenuId(), funcIds);
					}
				}
				
				//获取子菜单实体列表
				List<Menu> subMenus = menuService.getListByMenuIds(menuIds);
					
				//删除重复菜单
				subMenu = new ListUtil<Menu>().removeRepeat(subMenus, subMenu);
					
				//获取全部功能列表
				List<Function> functions = functionService.getList();
					
				//实例化功能实体集合
				List<Function> funcMaps = null;
					
				//遍历菜单
				for(Iterator<Menu> m = subMenu.iterator(); m.hasNext();){
					Menu menu = m.next();
					//实例化新的集合
					funcMaps = new ArrayList<Function>();
					//从集合中取出功能
					funcIds = (String)functionMap.get("menu" + menu.getId());
					//logger.info("menuId: " + menu.getId() + "funcIds: " + funcIds);
					//把功能集合转成数组
					String[] funcs = funcIds.split(",");
					//遍历功能列表
					for(Iterator<Function> f = functions.iterator(); f.hasNext();){
						//实体化功能
						Function fun = f.next();
						//遍历集合中的功能ID
						for(int i = 0; i < funcs.length; i++){
							//如果功能ID = 集合中功能ID
							if(String.valueOf(fun.getId()).equalsIgnoreCase(funcs[i])){
								//把功能实体加入到功能实体集合
								funcMaps.add(fun);
							}
						}
					}
					//把功能实体集合保存到菜单集合中
					functionMap.put("menu" + menu.getId(), funcMaps);					
				}
				
				//遍历子菜单获取主菜单
				for(Iterator<Menu> a = subMenu.iterator();a.hasNext();){
					Menu menu = a.next();
					//增加主菜单
					menus.add(menu.getMainMenu());
				}
				
			//List<Menu> list = authorityService.getMenuByAuthoritys(authoritys);
			//menus.addAll(list);
				
				//删选重复菜单
				menus = new ListUtil<Menu>().removeRepeat(menus);
				
				//根据menuOrder进行排序
				Collections.sort(menus, new Comparator<Menu>() {  
			        public int compare(Menu m1, Menu m2) {  
			        	return m1.getMenuOrder()-m2.getMenuOrder() ;   
			        }  
				});  
				
				//把用户存入session
				session.put("user", loginUser);
				//把人员信息存入Session
				session.put("person", person);
				//把部门信息存入Session
				session.put("depart", depart);
				//把菜单信息存入session
				session.put("menus", menus);
				//把子菜单列表加入到 SESSION中
				session.put("subMenus", subMenus);
				//把功能列表写入 SESSION中
				session.put("function", functionMap);
				
				result = "loginSuccess";
				logger.info("用户登录结束=============================================================================================");

			}

			logger.info("result: " + result);
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return SUCCESS;
	}

	
	/**
	 * 登出系统
	 * @return
	 */
	public String logout(){
		if(session.containsKey("user")){
			session.remove("user");
		}
		if(session.containsKey("person")){
			session.remove("person");
		}
		if(session.containsKey("depart")){
			session.remove("depart");
		}
		if(session.containsKey("menus")){
			session.remove("menus");
		}
		if(session.containsKey("subMenus")){
			session.remove("subMenus");
		}
		if(session.containsKey("function")){
			session.remove("function");
		}
		return "logout";
	}
	
	/**
	 * 获取用户权限中的功能
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String loadUserMainMenu(){
		List<Menu> menus = (List<Menu>)session.get("menus");
		boolean state = false;
		StringBuffer sb = new StringBuffer();

		for(Iterator<Menu> i = menus.iterator();i.hasNext();){
			if(state){
				sb.append(",");
			}
			Menu menu = i.next();		
			sb.append(menu.getId());
			state = true;
		}
		result = sb.toString();		
		return SUCCESS;
	}
	
	
	/**
	 * 页面跳转
	 */
	public String show(){	
		//获取权限
		functions = getAutFunctions();
		//获取用户
		T_User user = (T_User)session.get("user");
		departId = user.getPerson().getDepart().getId();
		curDepartId = departId;
		return "show";
	}
	
	/**
	 * 删除用户
	 */
	public String delete(){
		//userService.falseDelete(id);
		return SUCCESS;
	}
	
	/**
	 *	读取数据条数 
	 */
	public String loadUsersDataCount(){
		totalCount = userService.getCountByDepartId(curDepartId);
		return SUCCESS;
	}
	
	/**
	 *	用户数据读取 
	 * @throws ParseException 
	 */
	public String loadUsersData() throws ParseException{
		try{
			List<UserVo> userVos = new ArrayList<UserVo>();
			List<T_User> users = userService.getListForPageByDepartId(curDepartId, pageNo, pageSize);	//获取用户列表
			Long userCount = userService .getCountByDepartId(curDepartId);	//统计用户数量
	
			//遍历用户 把用户变成VO
			for(Iterator<T_User> i = users.iterator();i.hasNext();){
				T_User user = i.next();
				Person person = user.getPerson();
				Department depart = person.getDepart();	//获取部门
				UserVo userVo = new UserVo();	//实例化VO
				userVo.setId(user.getId());
				userVo.setLoginName(user.getLoginName());	//用户名
				userVo.setName(person.getName());	//姓名
				userVo.setPhone(person.getPhone());	//电话
				userVo.setPassword(user.getPassword());	//密码
				userVo.setSn(user.getSn());	//编码
				userVo.setDepartName(depart.getName());	//设置部门
				userVo.setDepartId(depart.getId());	//设置部门ID
				userVo.setSex(person.getSex());
				userVo.setStatus(user.getStatus());
				userVo.setLocked(user.getLocked());
				
				//遍历角色
				String roleNames = "";
				String roleIds = "";
				boolean firstState = true;
				for(Iterator<Role> j = person.getRoles().iterator();j.hasNext();){
					Role role = j.next();
					if(!firstState){
						roleNames +=",";
						roleIds +=",";
					}
					roleNames+=role.getRoleName();
					roleIds+=role.getRoleId();
					firstState = false;
	
				}
				userVo.setStrRoleIds(roleIds);	//设置角色组
				userVo.setRoleNames(roleNames);	//设置角色ID组
					
				if(person.getJobDate() != null){
					userVo.setJobDate(sdf.format(person.getJobDate()));
				}
				if(person.getBirthday() != null){
					userVo.setBirthday(sdf.format(person.getBirthday()));
				}
				userVos.add(userVo);
			}
			
			DataGridVo<UserVo> userDataGridVo = new DataGridVo<UserVo>();
			userDataGridVo.setTotal(userCount);
			userDataGridVo.setRows(userVos);
			
			String jsonResult = JSONObject.fromObject(userDataGridVo).toString();
	
			response.getWriter().write(jsonResult);
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	
	//编辑个人信息
	public String pl_info(){
		return "pl_info";
	}
	
	/**
	 *	个人信息数据读取
	 */
	public String loadUserEditData(){
		List<UserVo> userVos = new ArrayList<UserVo>();
		T_User user = (T_User)session.get("user");
		user = userService.get(user.getId());	//获取用户列表
		Person person = user.getPerson();
		Department depart = person.getDepart();	//获取部门
		UserVo userVo = new UserVo();	//实例化VO
		userVo.setId(user.getId());
		userVo.setLoginName(user.getLoginName());	//用户名
		userVo.setName(person.getName());	//姓名
		userVo.setPhone(person.getPhone());	//电话
		userVo.setPassword(user.getPassword());	//密码
		userVo.setSn(user.getSn());	//编码
		userVo.setDepartName(depart.getName());	//设置部门
		userVo.setDepartId(depart.getId());	//设置部门ID
		userVo.setSex(person.getSex());		//设置性别
		userVo.setStatus(user.getStatus());	//设置状态
		userVo.setLocked(user.getLocked());	//设置帐号锁
		
		//遍历角色
		String roleNames = "";
		String roleIds = "";
		boolean firstState = true;
		for(Iterator<Role> j = person.getRoles().iterator();j.hasNext();){
			Role role = j.next();
			if(!firstState){
				roleNames +=",";
				roleIds +=",";
			}
			roleNames+=role.getRoleName();
			roleIds+=role.getRoleId();
			firstState = false;

		}
		userVo.setStrRoleIds(roleIds);	//设置角色组
		userVo.setRoleNames(roleNames);	//设置角色ID组

		
		if(person.getJobDate() != null){
			userVo.setJobDate(sdf.format(person.getJobDate()));
		}
		if(person.getBirthday() != null){
			userVo.setBirthday(sdf.format(person.getBirthday()));
		}
		userVos.add(userVo);
	
		DataGridVo<UserVo> userDataGridVo = new DataGridVo<UserVo>();
		userDataGridVo.setRows(userVos);
	
		String jsonResult = JSONObject.fromObject(userDataGridVo).toString();
		try{
			response.getWriter().write(jsonResult);
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 增加新用户
	 * @throws ParseException 
	 */
	public String add() throws ParseException{
		//设置角色列表
		Set<Role> setRoles = new HashSet<Role>();	
		List<Role> listRoles = roleService.getListByIds(roles);
		setRoles.addAll(listRoles);
		
		//设置PERSON
		Person person = new Person();
		person.setName(name);	//姓名
		person.setSex(sex);	//性别
		person.setBirthday(null);	//出生日期
		if(birthday.length() != 0){
			person.setBirthday(sdf.parse(birthday));	
		}
		person.setJobDate(null);	//工作时间
		if(jobDate.length() != 0){
			person.setJobDate(sdf.parse(jobDate));
		}
		person.setPhone(phone);	//电话
		person.setDepart(departService.get(departId));	//设置部门

		person.setRoles(setRoles);	//设置角色
		personService.save(person);
		
		//设置用户
		T_User user = new T_User();
		user.setLoginName(loginName);	//用户名
		user.setPassword(W7.encode(password));	//密码
		user.setSn(sn);	//编号
		user.setStatus(status);	//状态
		user.setLocked(locked);	//锁定
		user.setCreateDate(new Date());	//创建时间
		user.setPerson(person);
		userService.save(user);
		return SUCCESS;
	}
	
	/**
	 * 用户信息编辑, 个人信息编辑
	 * @throws ParseException 
	 */
	public String edit() throws ParseException{
		try{
			//设置角色列表
			Set<Role> setRoles = new HashSet<Role>();	
			List<Role> listRoles = roleService.getListByIds(roles);
			System.out.println("listRoles: " + listRoles.size());
			setRoles.addAll(listRoles);
			
			//Person person = new personService.get(id);
			//设置用户
			T_User user = userService.get(id);
			//设置PERSON
			Person person = user.getPerson();
			person.setName(name);	//姓名
			person.setSex(sex);	//性别
			person.setBirthday(null);	//出生日期
			if(birthday.length() != 0){
				person.setBirthday(sdf.parse(birthday));	
			}
			person.setJobDate(null);	//工作时间
			if(jobDate.length() != 0){
				person.setJobDate(sdf.parse(jobDate));
			}
			person.setPhone(phone);	//电话
			person.setDepart(departService.get(departId));	//设置部门
			System.out.println("setRoles: " + setRoles);
			person.setRoles(setRoles);	//设置角色
			personService.update(person);
			
			//设置用户
			user.setLoginName(loginName);	//用户名
			if(!password.equalsIgnoreCase("")){
				user.setPassword(W7.encode(password));	//密码
			}
			user.setSn(sn);	//编号
			user.setStatus(status);	//状态
			user.setLocked(locked);	//锁定
			user.setCreateDate(new Date());	//创建时间
			userService.update(user);
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	/**
	 * 验证登录名是否重复
	 */
	public String checkLoginName(){
		T_User user = userService.getByName(loginName);
		if(user==null){
			result="true";
		}else{
			result="false";
		}
		return SUCCESS;
	}
	
	/**
	 * 判断 部门里是否存在用户
	 */
	public String existUserByDepart(){
		System.out.println("departId: " + departId);
		if(userService.existUserByDepartId(departId)){
			result="true";
		}else{
			result="false";
		}
		return SUCCESS;
	}

	/**
	 *  Gets And Sets
	 */

	public T_User getUser() {
		return user;
	}

	public void setUser(T_User user) {
		this.user = user;
	}
	
	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getLoginName() {
		return loginName;
	}

	public void setLoginName(String loginName) {
		this.loginName = loginName;
	}

	public String getRoles() {
		return roles;
	}

	public void setRoles(String roles) {
		this.roles = roles;
	}
	
	public int getPageNo() {
		return pageNo;
	}

	public void setPageNo(int pageNo) {
		this.pageNo = pageNo;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}
	
	public int getDepartId() {
		return departId;
	}

	public void setDepartId(int departId) {
		this.departId = departId;
	}

	public int getCurDepartId() {
		return curDepartId;
	}

	public void setCurDepartId(int curDepartId) {
		this.curDepartId = curDepartId;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public long getTotalCount() {
		return totalCount;
	}

	public void setTotalCount(long totalCount) {
		this.totalCount = totalCount;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public String getSn() {
		return sn;
	}

	public void setSn(String sn) {
		this.sn = sn;
	}

	public String getJobDate() {
		return jobDate;
	}

	public void setJobDate(String jobDate) {
		this.jobDate = jobDate;
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public String getLocked() {
		return locked;
	}

	public void setLocked(String locked) {
		this.locked = locked;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public String getBirthday() {
		return birthday;
	}

	public void setBirthday(String birthday) {
		this.birthday = birthday;
	}

	public List<FunctionVo> getFunctions() {
		return functions;
	}

	public void setFunctions(List<FunctionVo> functions) {
		this.functions = functions;
	}
	

	
}
